package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.feignclient.CheckCodeClient;
import com.xuecheng.mapper.XcUserMapper;
import com.xuecheng.model.dto.AuthParamsDTO;
import com.xuecheng.model.po.XcUser;
import com.xuecheng.model.vo.XcUserExtVO;
import com.xuecheng.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 账号密码认证
 */
@Slf4j
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
	
	@Resource
	private XcUserMapper xcUserMapper;
	@Resource
	private PasswordEncoder passwordEncoder;
	@Resource
	private CheckCodeClient checkCodeClient;
	
	//实现账号和密码认证
	@Override
	public XcUserExtVO execute(AuthParamsDTO authParamsDto) {
		//得到验证码
		String checkcode = authParamsDto.getCheckcode();
		String checkcodekey = authParamsDto.getCheckcodekey();
		if (StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)) {
			log.error("验证码为空");
			throw new RuntimeException("验证码为空");
		}
		
		//校验验证码,请求验证码服务进行校验
		Boolean result = checkCodeClient.verify(checkcodekey, checkcode);
		if (result == null || !result) {
			log.error("验证码错误");
			throw new RuntimeException("验证码错误");
		}
		
		//账号
		String username = authParamsDto.getUsername();
		//从数据库查询用户信息
		XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
		if (xcUser == null) {
			//账号不存在
			log.error("账号不存在");
			throw new RuntimeException("账号不存在");
		}
		//比对密码
		String passwordDB = xcUser.getPassword();//正确的密码(加密后)
		String passwordInput = authParamsDto.getPassword();//输入的密码
		boolean matches = passwordEncoder.matches(passwordInput, passwordDB);
		if (!matches) {
			throw new RuntimeException("账号或密码错误");
		}
		XcUserExtVO xcUserExtVO = new XcUserExtVO();
		BeanUtils.copyProperties(xcUser, xcUserExtVO);
		return xcUserExtVO;
	}
}
